
/**
 * Default load in when page loads
 */
$(document).ready (function () {
	if(isUserLoggedIn() == "true"){ //User is signed in
		$('#userMenu').load("includes/functions/loggedin.php");
	}else {
		$("#userMenu").load("includes/sitePages/sidebarLoginModule.html");
	}
});

/*
 * Checks if user is logged in or no	
 * @returns string true or false
 */
function isUserLoggedIn(){
	var res = "";
	$.ajax({
		url: "includes/functions/isLoggedIn.php",
		async: false,					// To be able to return info
		success: function (data){
			res = data.respond;
		}
	});
	return res;
}

/**
 * Checks that form input is valid
 * @param form new userform
 */

function newUserFormCheck(form){
	var string = ""; // Information string
	var error = "";	//Alert string	
	/*
	 * If both of the username fields are empty, display alert and change CSS
	 */
	if(form.userName.value == ""  || form.userName2.value == "" ){	
		$('#userName').removeClass("has-success");
		$('#userName span').removeClass("glyphicon-ok");
		$('#userName').addClass(" has-error");
		$('#userName span').addClass(" glyphicon-remove");
		$('#userName2').removeClass("has-success");
		$('#userName2 span').removeClass("glyphicon-ok");
		$('#userName2').addClass("has-error");
		$('#userName2 span').addClass("glyphicon-remove");
		string = "<li>Skrive inn brukernavn to ganger?</li>";
	}else{
		//If both of the username fields are not empty, display alert and change CSS to green
		$('#userName').removeClass(" has-error");
		$('#userName span').removeClass(" glyphicon-remove");
		$('#userName').addClass(" has-success");
		$('#userName span').addClass(" glyphicon-ok");
		$('#userName2').removeClass(" has-error");
		$('#userName2 span').removeClass(" glyphicon-remove");
		$('#userName2').addClass(" has-success");
		$('#userName2 span').addClass(" glyphicon-ok");
	}
	/*
	 * If username is allready in use, display alert, change css and reset the fields,
	 */
	if(checkUserName(form.userName.value) == "true"){ //checks if username is allready in use
		$('#userName').removeClass(" has-success");
		$('#userName span').removeClass(" glyphicon-ok");
		$('#userName').addClass(" has-error");
		$('#userName span').addClass(" glyphicon-remove");
		$('#userName2').removeClass(" has-success");
		$('#userName2 span').removeClass(" glyphicon-ok");
		$('#userName2').addClass(" has-error");
		$('#userName2 span').addClass(" glyphicon-remove");
		$('#userName input').val("");
		$('#userName2 input').val("");
		error += "<li>Brukernavnet er allerdede i bruk!</li>";
	}	
	// If the email field is empty, display alert, change css
	if(form.email.value == ""){
		$('#email').removeClass(" has-success");
		$('#email span').removeClass(" glyphicon-ok");
		$('#email').addClass(" has-error");
		$('#email span').addClass(" glyphicon-remove");
		string = string+"<li>Fylt ut epostadressen din?</li>";
	}	
	//If the email allready exists in the DB, display alert, change css, and reset form value
	if (checkUserEmail(form.email.value) == "true"){ 
		$('#email').removeClass(" has-success");
		$('#email span').removeClass(" glyphicon-ok");
		$('#email').addClass(" has-error");
		$('#email span').addClass(" glyphicon-remove");
		$('#email input').val("");
		error += "<li>Eposten er allerdede registrert!</li>";
	}	
	// If the passwords field are not equal, change css and display alert, and reset the formvalues
	if(form.pwd.value != form.pwd2.value){
		form.pwd.value = "";
		form.pwd2.value = "";
		$('#pwd').removeClass(" has-success");
		$('#pwd span').removeClass(" glyphicon-ok");
		$('#pwd').addClass(" has-error");
		$('#pwd span').addClass(" glyphicon-remove");
		$('#pwd2').removeClass(" has-success");
		$('#pwd2 span').removeClass(" glyphicon-ok");
		$('#pwd2').addClass(" has-error");
		$('#pwd2 span').addClass(" glyphicon-remove");
		error += "<li>Passord må være like!</li>";
	}
	//If the password field are empty, change css and display alert
	if(form.pwd.value == "" || form.pwd2.value == ""){
		$('#pwd').removeClass(" has-success");
		$('#pwd span').removeClass(" glyphicon-ok");
		$('#pwd').addClass(" has-error");
		$('#pwd span').addClass(" glyphicon-remove");
		$('#pwd2').removeClass(" has-success");
		$('#pwd2 span').removeClass(" glyphicon-ok");
		$('#pwd2').addClass(" has-error");
		$('#pwd2 span').addClass(" glyphicon-remove");
		string += "<li>Skrevet inn passordet ditt to ganger?</li>";
	}
	//If the name field are empty, change css and display alert
	if(form.name.value == ""){
		$('#name').removeClass(" has-success");
		$('#name span').removeClass(" glyphicon-ok");
		$('#name').addClass(" has-error");
		$('#name span').addClass(" glyphicon-remove");		
		string += "<li>Skrevet inn navnet ditt?</li>";
	}
	//If the string var is not empty, display the alert with the text in the string var.
	if(string != ""){
		string = "<strong>Isjda, har du:</strong><ul>"+string+"</ul>";
		alert.info("#alertRegUser_placeholder", string);
	}
	//If the error var is not empty, display the alert with the text in the error var.
	if(error != ""){
		error = "<strong>Ånei! Dette gikk galt fordi:</strong><ul>"+error+"</ul>";
		alert.danger("#alertRegUser_placeholder", error);
	}	
	//If there are no text inside the string var or error var, then no errors, send information to DB
	if(string == "" && error == ""){
		createNewUser(form); 
	}
}

/**
 * Checks input on change user form
 * @param form values from ChangeUser form
 */

function changeUserFormCheck(form){
	var string = ""; // Information string
	var error = "";	//Alert string	
	// If the email field is empty, display alert, change css
	if(form.email.value == ""){
		$('#email').removeClass(" has-success");
		$('#email span').removeClass(" glyphicon-ok");
		$('#email').addClass(" has-error");
		$('#email span').addClass(" glyphicon-remove");
		string += "<li>Fylt ut epostadressen din?</li>";
	}
	//If the email allready exists in the DB, display alert, change css
	if(checkUserEmail(form.email.value) == "true"){ 
		$('#email').removeClass(" has-success");
		$('#email span').removeClass(" glyphicon-ok");
		$('#email').addClass(" has-error");
		$('#email span').addClass(" glyphicon-remove");
		$('#email input').val("");
		error += "<li>Epostadressen finnes allerde fra før!</li>";
	}
	// If the password fields are empty change css and display alert, and reset form values
	if((form.pwd.value !="" && form.pwd2.value !="") && form.oldpwd.value == ""){
		form.pwd.value = "";
		form.pwd2.value = "";
		$('#oldpwd').addClass(" has-error");
		$('#oldpwd span').addClass(" glyphicon-remove");
		$('#pwd').removeClass(" has-success");
		$('#pwd span').removeClass(" glyphicon-ok");
		$('#pwd').addClass(" has-error");
		$('#pwd span').addClass(" glyphicon-remove");
		$('#pwd2').removeClass(" has-success");
		$('#pwd2 span').removeClass(" glyphicon-ok");
		$('#pwd2').addClass(" has-error");
		$('#pwd2 span').addClass(" glyphicon-remove");
		string += "<li>Å skrive inn ditt gjelende passord?</li>";
	}
	// If the new passwords field are not equal, change css and display alert, and reset the formvalues
	if(form.pwd.value != form.pwd2.value){
		form.pwd.value = "";
		form.pwd2.value = "";
		$('#pwd').removeClass(" has-success");
		$('#pwd span').removeClass(" glyphicon-ok");
		$('#pwd').addClass(" has-error");
		$('#pwd span').addClass(" glyphicon-remove");
		$('#pwd2').removeClass(" has-success");
		$('#pwd2 span').removeClass(" glyphicon-ok");
		$('#pwd2').addClass(" has-error");
		$('#pwd2 span').addClass(" glyphicon-remove");
		error += "<li>Passord må være like!</li>";
	}
	//If the name field are empty, change css and display alert
	if(form.name.value == ""){
		$('#name').removeClass(" has-success");
		$('#name span').removeClass(" glyphicon-ok");
		$('#name').addClass(" has-error");
		$('#name span').addClass(" glyphicon-remove");
		string += "<li>Skrevet inn navnet ditt?</li>";
	}	
	//If the string var is not empty, display the alert with the text in the string var.
	if(string != ""){ 
		string = "<strong>Isjda, har du:</strong><ul>"+string+"</ul>";
		alert.info("#alertChangeUser_placeholder", string);
	}
	//If the error var is not empty, display the alert with the text in the error var.
	if(error != ""){  
		error = "<strong>Ånei! Dette gikk galt fordi:</strong><ul>"+error+"</ul>";
		alert.danger('#alertChangeUser_placeholder', error);
	}	
	//If there are no text inside the string var or error var, then no errors, send information to DB
	if(string == "" && error == ""){ // if no error, do ajax call function
		updateUser(form);
	}
}



/**
 * Alert functions
 * four different colors
 * @param id div tag to place the alert
 * @param message the alert message 
 */
function mainAlert(id){
    window.setTimeout(function() {		//Fades and slides out the alert
  	  $(id).fadeTo(500, 0).slideUp("500", function(){ 
  		  $(id).removeAttr('style');
  		  $(id).empty();
  	  });
  	}, 5000);
}
/**
 * Alerting/informing the user
 * @param id, html element ID
 * @param message, the alert text
 */
alert.warning = function(id ,message){
	$(id).html('<br/><div class="alert alert-warning"><span>'+message+'</span></div>');
	//Based on where the alert shall be viewed
	if(id == "#alert_placeholder_mainPage"){
		mainAlert(id);
	}
	if(id == "#alertChangeUser_placeholder" || id == "#alertRegUser_placeholder"){
		$(id).addClass("in");
	}
};

alert.info = function(id, message){
	$(id).html('<br/><div class="alert alert-info"><span>'+message+'</span></div>');
	//Based on where the alert shall be viewed
	if(id == "#alert_placeholder_mainPage"){
		mainAlert(id);
	}
	if(id == "#alertChangeUser_placeholder" || id == "#alertRegUser_placeholder"){
		$(id).addClass("in");
	}
};

alert.danger = function(id, message){
	$(id).html('<br/><div class="alert alert-danger"><span>'+message+'</span></div>');
	//Based on where the alert shall be viewed
	if(id == "#alert_placeholder_mainPage"){
		mainAlert(id);
	}
	if(id == "#alertChangeUser_placeholder"  || id == "#alertRegUser_placeholder"){
		$(id).addClass("in");
	}
};

alert.success = function(id, message){
	//Based on where the alert shall be viewed
	$(id).html('<br/><div class="alert alert-success"<span>'+message+'</span></div>');
	if(id == "#alert_placeholder_mainPage"){
		mainAlert(id);
	}
	if(id == "#alertChangeUser_placeholder"  || id == "#alertRegUser_placeholder"){
		$(id).addClass("in");
	}
};

/**
 * Ajax call to check if username is allready in use
 * @param string username
 * @return string "true" or "false"
 */
function checkUserName(string){
	var res = ""; 
	$.ajax({
		url: 'includes/functions/createUser.php',
		type: 'post',
		async: false,
		data: {
			userNameCheck: "true",
			userName: string
		},
		success: function(data){
			res = data.respond;
		}
	});
	return res;
}

/**
 * ajax call to check if Email is allready in DB
 * @param string email
 * @return string "true" or false
 */
function checkUserEmail(string){
	var res = "";
	$.ajax({
		url: 'includes/functions/createUser.php',
		type: 'post',
		async: false,
		data: {
			emailCheck: "true",
			email: string
		},
		success: function(data){	
			res = data.respond;
		}
	});
	return res;
};

/**
 * Ajax call to insert a new user in the Database
 * @param form values from RegUserForm
 * @return alert
 */
function createNewUser(form){
	$.ajax({
		url: 'includes/functions/createUser.php',	//PHP file to do the serverside work
		type: 'post',								//How to pass data to the PHP file
		data: {userName: form.userName.value,		// The formValues
			email: form.email.value,
			pwd: form.pwd.value,
			userRealName : form.name.value,
			town :  form.homeTown.value
			},		
		success: function(data){					//If Ajax ==Success
			if(data.respond == 'OK') {				//Response from the PHP file
				$('#regUser').modal('hide');
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();//Hide window
				page.init();						//Reload page
											//Inform the user
				alert.success("#alert_placeholder_mainPage","Du har nå blitt registrert, logg inn i menyen til venstre!");
			}else {
				$('#regUser').modal('hide'); 	
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();// If the PHP do not return OK
				alert.danger("#alert_placeholder_mainPage", data.respond);	
			}			
		},										//If the Ajax call dont goes throw
		error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert.danger('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
            	alert.danger('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
            	alert.danger('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
            	alert.danger('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
            	alert.danger('Time out error.');
            } else if (exception === 'abort') {
            	alert.danger('Ajax request aborted.');
            } else {
            	alert.danger('Uncaught Error.\n' + jqXHR.responseText);
            }
		}
			
	});
}

/**
 * This fetch user information based on the Session['user'] to the Change User form.
 * These values that are returned from the ajax call is prefilled in the form
 * @return user information into form inputs
 */
function changeUser(){
	$('#changeUserContent').load('includes/sitePages/changeUserModule.html');
	$.ajax({
		url: "includes/functions/getUserInfo.php",
		success: function(data){
			if(data.response == "true"){
				$("#userName input").val(data.userName);
				$("#email input").val(data.email);
				$("#email2 input").val(data.email);
				$("#name input").val(data.userRealName);
				$("#town input").val(data.town);
			}
		}
	});
							//Opens the modal window
	$('#changeUser').modal('show');
}
/**
 * This function is the acctuall function that updates the userinformation
 * @param form, input values
 * @return Hide modal
 */
function updateUser(form){	
	$.ajax({
		url: "includes/functions/updateUserInfo.php",
		type: "post",
		data: {email: form.email.value,
		oldpwd: form.oldpwd.value,
		pwd: form.pwd.value,
		name : form.name.value,
		town :  form.homeTown.value},
		success: function(data){	
			console.log(data.response);
			if(data.response == "true"){				
				$('#userMenu').load("includes/functions/loggedin.php"); 		//reloads the usermenu
																				//informs the user
				alert.success("#alert_placeholder_mainPage", "Bruker detaljer er nå oppdatert!");	
			}else if(data.response == "noChanges"){ 					//If no changes were made
				alert.info("#alert_placeholder_mainPage", "Ingen bruker detaljer ble oppdatert!");				
			}else{														//Error code
				alert.danger("#alert_placeholder_mainPage", data.response);								
			}			
		},
		error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert.danger('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
            	alert.danger('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
            	alert.danger('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
            	alert.danger('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
            	alert.danger('Time out error.');
            } else if (exception === 'abort') {
            	alert.danger('Ajax request aborted.');
            } else {
            	alert.danger('Uncaught Error.\n' + jqXHR.responseText);
            }
		}
	});
	$('#changeUser').modal('hide');
	$('body').removeClass('modal-open');
	$('.modal-backdrop').remove();
}
/**
 * Signin a user.
 * @param form, signIn form values
 * @return
 */
function signIn(form){
	$.ajax({									//Signing in the user by using ajax call
		url: 'includes/functions/login.php',
		type: 'post',
		data: {'uname': form.uname.value, 'pwd': form.pwd.value},
		success: function(data) {
			if(data.ok == 'OK') {
				$('#login').modal('hide');
				$('body').removeClass('modal-open');
				$('.modal-backdrop').remove();//Reload the firstpage to enable the menu
				page.init();
				$('#userMenu').load("includes/functions/loggedin.php");
			} else {							//Alerts the user if username/password is wrong.
				$("#login div").first().show();
				$("#login input").val('');
				$("#login input").first().get(0).focus();
				$("#loginFailure").removeAttr("style");
				$("#loginFailure").addClass("in");
			}
		}
	});
};
/**
 * Signs the user out of the website and informs the user about this and reloads the apge
 * to hide the user menu
 * @return
 */
function signOut(){
	$.ajax({
		url: 'includes/functions/logout.php',
		success: function(data){
			if(data.respons == 'true'){
				$("#userMenu").load("includes/sitePages/sidebarLoginModule.html");
				page.init();					// Load the first page again 
				alert.success("#alert_placeholder_mainPage", "Du er nå <strong>logget ut</strong>");
			}else {
				alert.danger("#alert_placeholder_mainPage",data.respond);
			}
		}
	});
}
